package top.lingkang.securityoauth2.server.store.impl;

import org.springframework.data.redis.core.RedisTemplate;
import top.lingkang.securityoauth2.core.entity.AccessToken;
import top.lingkang.securityoauth2.core.entity.RefreshToken;
import top.lingkang.securityoauth2.core.entity.UserDetail;
import top.lingkang.securityoauth2.server.common.CommonServer;
import top.lingkang.securityoauth2.server.config.Oauth2ServerProperties;
import top.lingkang.securityoauth2.server.store.TokenStore;

/**
 * @author lingkang
 * Created by 2022/7/1
 */
public class RedisTokenStore implements TokenStore {
    private RedisTemplate redisTemplate;
    private Oauth2ServerProperties serverProperties;

    public RedisTokenStore(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        serverProperties = CommonServer.serverProperties;
    }

    @Override
    public AccessToken getAccessToken(String token) {
        Object o = redisTemplate.opsForValue().get("access_token." + token);
        if (o == null)
            return null;
        return (AccessToken) o;
    }

    @Override
    public UserDetail getUserDetail(String token) {
        Object o = redisTemplate.opsForValue().get("user_detail." + token);
        if (o == null)
            return null;
        return (UserDetail) o;
    }

    @Override
    public RefreshToken getRefreshToken(String refreshToken) {
        Object o = redisTemplate.opsForValue().get("refresh_token." + refreshToken);
        if (o == null)
            return null;
        return (RefreshToken) o;
    }

    @Override
    public String getTokenByRefreshToken(String refreshToken) {
        Object o = redisTemplate.opsForValue().get("refresh_token-token." + refreshToken);
        if (o == null)
            return null;
        return (String) o;
    }

    @Override
    public void setAccessToken(String token, AccessToken accessToken) {
        redisTemplate.opsForValue().set("access_token." + token, accessToken, serverProperties.getRefreshTokenValid());
    }

    @Override
    public void setRefreshToken(String refreshToken, RefreshToken refresh_token) {
        redisTemplate.opsForValue().set("refresh_token." + refreshToken, refresh_token, serverProperties.getRefreshTokenValid());
    }

    @Override
    public AccessToken removeAccessToken(String token) {
        AccessToken accessToken = getAccessToken(token);
        if (accessToken != null)
            redisTemplate.delete("access_token." + token);
        return accessToken;
    }

    @Override
    public RefreshToken removeRefreshToken(String refreshToken) {
        RefreshToken rt = getRefreshToken(refreshToken);
        if (rt != null)
            redisTemplate.delete("refresh_token." + refreshToken);
        return rt;
    }
}
